﻿var rate = $.cookie("ParcelRate") || 1;
var parcel;
var orderID;
var scrollToph;
var  notbtn=""; //1有按钮
var app_url=location.origin;
var curstate = 0; //当前类别选项
var datalist = {};
(function(){
	OrderSearch();
	var order={
		init:function(){
			//导航栏的选中
            $('.wrapper').navbarscroll();
            $("#categories li").eq(2).addClass("cur").siblings().removeClass("cur");
			this.BindEvents();
		},
		BindEvents:function(){
			var self = this;
			if(APP){
				$("#order_term_btn").remove();
            }
            
             //售价算价格
             $("#_confirmPrice").bind('input propertychange',function(){
                var val=Number($(this).val());
                var rate=Number($("#_salesRate").val());
                var usd_p=formatUSDPrice(val/rate);
                $("#_BEFPrice").val(usd_p);
            });
            $("#_BEFPrice").bind('input propertychange',function(){
                var val=Number($(this).val());
                var rate=Number($("#_salesRate").val());
                var usd_r=formatUSDPrice(val*rate);
                $("#_confirmPrice").val(usd_r);
            });
            $("#_salesRate").bind('input propertychange',function(){
                var rate=Number($(this).val());
                var val=Number($("#_confirmPrice").val());
                var usd_p=formatUSDPrice(val/rate);
                $("#_BEFPrice").val(usd_p);
            });
		            //筛选
            $("#order_term_btn").on("click", function () {
                if(APP){
                	var appJson={};
            		appJson.title=_("订单筛选");
            		appJson.url=app_url+"/Team/OrderFilter/?type=2";
            		YiYi_APP.showNewPage(JSON.stringify(appJson));
                }else{
                	location.href="/Team/OrderFilter/?type=2";
                }
            });
            $(".order-status span").on("click", function () { //订单状态选中
                $(this).addClass("active").siblings().removeClass("active");
            });
            //其他筛选条件点击添加样式、可多选
            $("#order_term_box").on("click", ".term span", function () {
                $(this).toggleClass("active");
            });
            $("#filter_product_btn").on("click", function () {
                $("#common_header").show();
                $("#order_term_btn").show();
                $("#order_term_box").hide();
                OrderSearch();
            });
			//点击全选
			$("#checkbox_check_all").on("click",function(){
				self.countCheck(0,0,0);//取消
				$(this).toggleClass("selected")
				if($(this).hasClass("selected")){
					$("#order .check_list_box").children("span").addClass("selected");
					$("#order .check_list_box span.selected").each(function (i, item) {
                        var pre = parseFloat($(item).closest("li").find(".first").text());//当前点击行的每卡

    					var totalprice = parseFloat($(item).closest("li").find(".CurrentRMB .product_list_price_rmb").attr('data-PurchaseRMB')*($(item).parent('.check_list_box').attr('data-weight')));
    					var usd_totalprice = parseFloat($(item).closest("li").find(".CurrentUSD .product_list_price_usd").attr('data-PurchaseUSD')*($(item).parent('.check_list_box').attr('data-weight')));

    					handleBtn();
						self.countCheck(1,pre,totalprice);
						self.countCheck(1,pre,usd_totalprice,"usd");
					});	
				}else{
					$(".check_list_box").children("span").removeClass("selected");
					clearAll();
					self.countCheck(0,0,0);//取消
				}
				
			});
			//列表的勾选框
			$("#order").on("click",".check_list_box",function(){
				$(this).children("span").toggleClass("selected");
                var pre = parseFloat($(this).closest("li").find(".first").text());//当前点击行的每卡

                var totalprice=parseFloat(($(this).closest("li").find(".CurrentRMB .product_list_price_rmb").attr('data-PurchaseRMB'))*($(this).attr('data-weight')));
                var usd_totalprice = parseFloat(($(this).closest("li").find(".CurrentUSD .product_list_price_usd").attr('data-PurchaseUSD'))*($(this).attr('data-weight')));



				//判断是否全选
				var length=$("#order .check_list_box span.checkbox").length;
				var checkLength=$("#order .check_list_box span.selected").length;
				if(checkLength>0){
					handleBtn();
				}else{
					clearAll();
				}
				
				if(length==checkLength){
					$("#checkbox_check_all").addClass("selected");
				}else{
					$("#checkbox_check_all").removeClass("selected");
				}				
				if($(this).children("span").hasClass("selected")){
					self.countCheck(1,pre,totalprice);//选中
					self.countCheck(1,pre,usd_totalprice,"usd");//选中
				}else{
					self.countCheck(2,pre,totalprice);//取消
					self.countCheck(2,pre,usd_totalprice,"usd");//取消
				}
				
			});
			
			//采购订单输入验证 class=purchase_form
            var validate = $(".purchase_form").validate({
                debug: true, //调试模式取消submit的默认提交功能   
                focusInvalid: false, //当为false时，验证无效时，没有焦点响应  
                onkeyup: false,
                submitHandler: function (form) {   //表单提交句柄,为一回调函数，带一个参数：form   
                    PurchaseOrder();//采购订单
                },
                rules: {
                    OriginSN:"required", 
                    Category:"required", 
                    Shape:"required", 
                    Size:"required",
                    Color: "required", 
                    Clarity: "required", 
                    Country: "required", 
                    DeliveryTime: "required", 
                    PurchaseRMB: "required", 
                    PriceUSD: "required", 
                    StyleNo: "required", 
                },
                messages: {
                    OriginSN:"", 
                    Category:"", 
                    Shape:"", 
                    Size:"",
                    Color: "", 
                    Clarity: "", 
                    Country: "",
                    DeliveryTime: "", 
                    PurchaseRMB: "", 
                    PriceUSD: "", 
                    StyleNo: "", 
                }
            });

            //回裸钻库输入验证 class=_backdia
            var validate = $("._backdia").validate({
                debug: true, //调试模式取消submit的默认提交功能   
                focusInvalid: false, //当为false时，验证无效时，没有焦点响应  
                onkeyup: false,
                submitHandler: function (form) {   //表单提交句柄,为一回调函数，带一个参数：form   
                    BackDia();//添加裸钻(回裸钻库)
                },
                rules: {                    
                    OriginSN:"required", 
                    Category:"required", 
                    Shape:"required", 
                    Size:"required",
                    Color: "required", 
                    Clarity: "required", 
//                  Country: "required", 
                    
                },
                messages: {
                    OriginSN:"", 
                    Category:"", 
                    Shape:"", 
                    Size:"",
                    Color: "", 
                    Clarity: "", 
//                  Country: "",
                }
            });
		},

        //统计数据
        countCheck:function(type,pre,totalPrice,usd){		
			var price=parseFloat($("#check-total-price").text());
			var usd_price=parseFloat($("#check-total-price-usd").text());
			var pre_price=parseFloat($("#check-m-rmb").text());
			var _num = $(".check_list_box span.selected").length;	
			if(type==1){//加				
				if(usd=="usd"){
					usd_price+=totalPrice
				}else{
					price+=totalPrice
					pre_price+=pre
				}
			}
			if(type==2){//减
				
				if(usd=="usd"){
					usd_price-=totalPrice
				}else{
					price-=totalPrice
					pre_price-=pre
				}
			}
			if(type==0){
				_num=0;
				price=0;
				usd_price=0;
				pre_price=0;
			}
			$("#check-num").text(_num);
			$("#check-m-rmb").text(formatRMBPrice(pre_price));
			if(menu_team_parcels_columns_PaymentStatus || RoleID ==1){
			    $("#check-total-price").text(formatRMBPrice(price));
            }else{
                $("#check-total-price").text('-');
            }
            if(menu_team_parcels_columns_ConfirmUSD || RoleID ==1){
                $("#check-total-price-usd").text(formatUSDPrice(usd_price));
            }else{
                $("#check-total-price-usd").text('-');
            }
		},

		
	}
	order.init();
})();
 
function GetData(data){
	var type=data.Category;
	if(type==1 || type==2){
		 return	"<b class='clarity'>"+data.Clarity+"</b>";
	}
	return "";
}

//绑定数据
        function BindingOrder(result) {
            var _result = eval('(' + result + ')');//eval()解析单个json对象
            if (_result.msgcode == false) {//获取库存失败
                $("#order .order-list").html('<div style="text-align:center;padding-top:20px;width:100%;">'+_result.msginfo+'</div>');
            } else { //获取库存成功
                _result = _result.msginfo;
                var lis = "";//多行数据
                for (var i = 0; i < _result.length ; i++) {//_result.length
					var li = ""; //单行
                    var data = _result[i];
                    var product_data=JSON.parse(data.InventoryAttribute);

                    var parcel_order_priceRMB=''; //卖/Ct ￥
                    if(menu_team_parcels_columns_ConfirmPrice || RoleID == 1){
                        parcel_order_priceRMB="<span class='CurrentRMB'>￥/Ct&nbsp;&nbsp;<b class='product_list_price_rmb' data-PurchaseRMB='"+data.PurchaseRMB+"'>" + formatRMBPrice(parseFloat(data.ConfirmRMB)) +"</b></span>"
                    }
                    var parcel_order_priceUSD=''; //卖/Ct $
                    if(menu_team_parcels_columns_ConfirmUSD || RoleID == 1){
                        parcel_order_priceUSD="<span class='CurrentUSD'>$/Ct&nbsp;&nbsp;<b class='product_list_price_usd' data-PurchaseUSD='"+data.PurchaseUSD+"'>" + formatUSDPrice(parseFloat(data.ConfirmUSD)) +"</b></span>"
                    }


					lis += "<li>"+
                    "<div>"+
                    "<div class='check_list_box' lang='"+data.CustomerID+"' data-weight='"+data.InventoryCount+"' data-first='"+data.ConfirmRMB+"' data-second='"+data.ConfirmUSD+"'  data-PaymentStatus='"+data.ReceiptStatus+"'  data-receiptStatus='"+data.PaymentStatus+"'  data-customerID='"+data.CustomerID+"' data-Balance='"+data.Balance+"'  data-USDBalance='"+data.USDBalance+"' >"+
                    "<span class='checkbox' name='checkbox' lang='" + data.OrderID + "' data='"+data.OrderStatus+"'></span></div>"+
                    "<div class='product_list' data-id="+data.OrderID +">"+
                    "<label class='product-parameter' data='"+data.Remarks+"' data-id='"+data.OrderID+"' lang='"+data.SalesExchangerate+"' style='display:none'  data-sn='"+product_data.OriginSN+"' data-pay='"+data.ReceiptStatus+"' ></label>"+
                    "<div class='list_img_box'>"+ShowImgOne(product_data)+"</div>"+
					"<div class='list_detail_box'>"+
					"<p>"+
					"<b class='category' style='float: left'>" + GetCategory("parcels",product_data.Category) + "</b><b style='float: left' title='货号'>"+product_data.OriginSN+"</b>" +

                    "<b class='size' style='float: left'>" + product_data.Size + "</b><b style='float: left' class='color'>" + GetText("parcels",product_data.Category,product_data.Color,"Color") + "</b>" +GetData(data)+
                    "<b class='weight' style='float: left'>" + product_data.Weight + "</b><b  style='float: left'class='clarity'>" + product_data.Clarity + "</b>"+
                    "<b class='place' style='float: left'>" + GetText("parcels",product_data.Category,product_data.Place,"Place") + "</b>" +
                        "<b class='shape' style='float: left' data='" + product_data.Shape + "'>" + GetText("parcels",product_data.Category,product_data.Shape,"Shape") + "</b>" +
                        "</p>"+
					"<div class='list_price'>"+
                        parcel_order_priceRMB+parcel_order_priceUSD+
					"<span class='status_box' style='margin-left:10px'>"+ReceiptStatusFormat(data.PaymentStatus)+"</span><span class='status_box' lang='"+data.OrderStatus+"'>"+UserOrderStatusFormat(data.OrderStatus)+"</span></div>"+
					"<div class='time_box'>"+_("下单日期")+"：<span class='order-time'>"+DateTimeFormat(data.CreateTime)+"</span></div>"+
					"</div></div>"+modify_boxsParcel(data)+
					"</li>";

					lis += li;//将单行加到多行
                }
                $("#order_list").html(lis);//加入到id为inventory的figures中
                currentShow();  //币种设置
                //   @*主题色start*@
			    $(document.createElement("script")).attr("src","/Js/ThemesColor.js").appendTo("html");
			    //  @*主题色end*@
            }
        }
        
   
//自留回库 12-15 
function BackDia_Js(me,gwRate) {
	categoryTypeShow(me);
    $.ajax({
        url: "/Team/GetOrderNew",//提交地址
        type: "POST",//提交方式
        data: "{'OrderID':'" + me.getAttribute("value") + "'}",
        contentType: "application/json; charset=utf-8",
        success: function (result) {
            var _result = eval('(' + result + ')');//eval()解析单个json对象
            if(_result.msgcode==true){
            _result = _result.msginfo;
            var data = _result;
            var data_parse = JSON.parse(data.InventoryAttribute)
            myApp.popup(".BackDia_box");

            $("#_orID").val(_result.OrderID);//12-16
            $("#_invID").val(_result.ID);
            $("#originSN").val(data_parse.OriginSN);
            $("#category").val(GetCategory("parcels",data.Category));
            
            $("#shape").val(GetText("parcels",data_parse.Category,data_parse.Shape,"Shape"));   //主石净度 
            $("#color").val(GetText("parcels",data_parse.Category,data_parse.Color,"Color"));
            $("#colorDesc").val(data_parse.ColorDesc);
            $("#Weight").val(data_parse.Weight);
            $("#size").val(data_parse.Size);
            $("#sizeDesc").val(data_parse.SizeDesc);
//          $("#clarity").val(_result.Clarity); //判断显示
//			$("#clarityDesc").val(_result.ClarityDesc);
            $("#supplier").val(_result.Supplier);
            $("#place").val(data_parse.Place);
//          $("#country").val(_result.Place);
//          $("#state").val(_result.State);
            $("#purchaseRemarks").val(_result.PurchaseRemarks);
            $("#isStock").val(data_parse.IsStock);
            $("#remark").val(data_parse.Remark);

//          //原采购部分 01-12 
			$("#back_purchaseExchange").val(_result.PurchaseExchangerate);//原采购汇率
			$("#sourceRMBGrain").val(Math.round(_result.PurchaseRMB)); //原人民币
			$("#sourceUSDPerGrain").val(Math.round(_result.PurchaseUSD)); //原USD

//          //买
//			$("#buyUSDPerGrain").val(Math.round(_result.BuyUSDPerGrain));//买美金
//			$("#buyRMBGrain").val(Math.round(_result.BuyRMBGrain));//买人民币
 			}else{
                $(".BackDia_box").hide();
                toast(_result.msginfo);     	
           	}

        }
    });
}    
//回库12-16
function BackDia(me){
    var requestDia = {};
    
    requestDia.OrderIDs = $("#_orID").val();
    requestDia.ID = $("#_invID").val();
    requestDia.OriginSN = $("#originSN").val();//货号
    requestDia.Category =$("#category").val();
    requestDia.Shape =$("#shape").val();
    requestDia.Color =$("#color").val();
    requestDia.ColorDesc =$("#colorDesc").val();
    requestDia.Weight = $("#weight").val();
    requestDia.Size =$("#size").val(); //大小
    requestDia.SizeDesc =$("#sizeDesc").val(); //大小描述
    requestDia.Clarity =$("#clarity").val(); //净度
    requestDia.ClarityDesc =$("#clarityDesc").val(); //净度描述
    requestDia.Supplier =$("#supplier").val(); //供应商 
//          requestDia.Place =$("#country").val(); //所在地国家
//          requestDia.State =$("#state").val(); //所在地省
    requestDia.Place =$("#place").val(); //所在地
    requestDia.IsStock =$("#isStock").val();
    requestDia.PurchaseRemarks = $("#purchaseRemarks").val();

//          原采购
	requestDia.PurchaseExchangerate = $("#backchaseExchange").val();//原采购汇率
	requestDia.ConfirmPrice = (parseFloat($("#back_purchaseRMBperCarat").val()) *  parseFloat($("#weight").val())).toFixed(1); // $("#sourceRMBGrain").val(); //原采购总价￥
    requestDia.PurchaseUSDPerGrain = (parseFloat($("#back_purchaseRMBperCarat").val()) *  parseFloat($("#weight").val()) * parseFloat($("#back_purchaseExchange").val())).toFixed(2);   //$("#back_purchaseUSDPerGrain").val();//原采购总价$
    

//          //买
	requestDia.BuyUSDPerGrain = $("#buyUSDPerGrain").val();//买美金
	requestDia.BuyRMBGrain = $("#buyRMBGrain").val();//买人民币

    $.ajax({
        url: "/Team/ModifyOnlineOrderNew",//提交地址
        type: "POST",//提交方式
        data: JSON.stringify(requestDia),
        contentType: "application/json; charset=utf-8",
        success: function (result) {
            var _result = eval('(' + result + ')');//eval()解析单个json对象

            if (_result.msgcode == false) {
                //添加失败(接口错误或程序内部错误)
                myApp.alert(_("新增失败")+"：" + _result.msginfo);
            } else {
                //添加成功
                if (_result.result == true) {
                    //{\"count\": 1, \"ids_insert\": [5158997], \"ids\": [5158997], \"ids_update\": [], \"result\": true, \"count_update\": 0, \"count_insert\": 1}
                    myApp.alert(_("成功条目")+"：" + _result.count + _("\n\n新增条目")+"：" + _result.count_insert + _("\n\n更新条目")+"：" + _result.count_update);
                    myApp.closeModal(".BackDia_box");
                    OrderSearch();
                } else {
                    //请求参数不符{\"msg\": \"\\u4ef7\\u683c\\u8f6c\\u6362\\u5931\\u8d25\", \"result\": false}
                    myApp.alert(_("新增失败")+"：" + _result.msg);
                }
            }
        }
    });
}

//采购订单
function modify_box(me) {
	categoryTypeShow(me);	
	currentPurShow(); //采购的币种设置
    $.ajax({
        url: "/Team/GetOrderNew",//提交地址
        type: "POST",//提交方式
        data: "{'OrderID':'" + me.getAttribute("value") + "','GoodsType':2}",
        contentType: "application/json; charset=utf-8",
        success: function (result) {
            var _result = eval('(' + result + ')');//eval()解析单个json对象
            if(_result.msgcode==true){
                _result = _result.msginfo;
                var data= _result;
                var data_parse=JSON.parse(data.InventoryAttribute)
                myApp.popup(".modify_pop_box");
            
            $("#_purOrderID").val(_result.OrderID);
            $("#_orderStat").val(_result.OrderStatus);//隐藏域11-3 
            $("#_purSupplier").val(_result.Supplier);
            $("#_purOriginSN").val(data_parse.OriginSN);
            $("#_purCategory").val(data_parse.Category);
            $("#_purShape").val(data_parse.Shape);
            $("#_purColor").val(data_parse.Color);
            $("#_purColorDesc").val(data_parse.ColorDesc);
            $("#_purWeight").val(data_parse.Weight);
            $("#_purSize").val(data_parse.Size);
            $("#_purSizeDesc").val(data_parse.SizeDesc);
            $("#_purInventoryCount").val(data.InventoryCount);
            //  console.log(GetText("parcels",data_parse.Category,data_parse.Shape,"Shape")) 
            $("#_purClarity").val(data_parse.Clarity);
            $("#_purClarityDesc").val(data_parse.ClarityDesc);
            $("#_purCountry").val(data_parse.Place);//所在地国家
            $("#_purState").val(_result.State);//所在地省
            $("#_purIsStock").val(data_parse.IsStock);
              
            $("#_purchaseExchange").val(_result.PurchaseExchangerate);  
            $("#_PurchaseRemarks").val(_result.PurchaseRemarks);  
            $("#_deliveryTime").val(DateTimeFormat(_result.ShipTime)); //发货时间  
            $("#_buyPriceUSD").val(PriceFormat(parseFloat(_result.PurchaseUSD).toFixed(2))); //买$/Ct
//                  $("#_buyPrice").val(parseFloat(_result.PurchaseRMB).toFixed(2)); //买人民币
                console.log(_result.PurchaseRMB)
            $("#_buyPrice").val(PriceFormat(parseFloat(_result.PurchaseRMB).toFixed(1))); //买￥/Ct
            }else{
                $(".modify_pop_box").hide();
                toast(_(_result.msginfo));
            }
            
        }
    });
}
        
  //采购订单8-20
function PurchaseOrder(me) {  

    var requestOrder = {};

    requestOrder.OrderID = $("#_purOrderID").val();
    requestOrder.OrderStatus = $("#_orderStat").val();//11-3
    requestOrder.OriginSN = $("#_purOriginSN").val();//货号
    requestOrder.Category =$("#_purCategory").val();
    requestOrder.Shape =$("#_purShape").val();
    requestOrder.Color =$("#_purColor").val();
    requestOrder.ColorDesc =$("#_purColorDesc").val();
    requestOrder.Weight = $("#_purWeight").val();
    requestOrder.Size =$("#_purSize").val(); //大小
    requestOrder.SizeDesc =$("#_purSizeDesc").val(); //大小描述
    requestOrder.Clarity =$("#_purClarity").val(); //净度
    requestOrder.ClarityDesc =$("#_purClarityDesc").val(); //净度描述
    requestOrder.Supplier =$("#_purSupplier").val(); //供应商 必传
    requestOrder.Place =$("#_purCountry").val(); //所在地国家
    requestOrder.State =$("#_purState").val(); //所在地省
    requestOrder.IsStock =$("#_purIsStock").val();
    requestOrder.ShipTime = $("#_deliveryTime").val();
    requestOrder.InventoryCount = $("#_purInventoryCount").val();
    
    requestOrder.PurchaseRemarks = $("#_PurchaseRemarks").val();
    
    requestOrder.PurchaseExchangerate = $("#_purchaseExchange").val(); //采购汇率
    requestOrder.PurchaseRMB =  $("#_buyPrice").val();//买RMB
    requestOrder.PriceUSD = $("#_buyPriceUSD").val();;//买美金
     

    $.ajax({
        url: "/team/PurchaseOrderNew",//提交地址
        type: "POST",//提交方式
        data: JSON.stringify(requestOrder),
        contentType: "application/json; charset=utf-8",
        success: function (result) {
            var _result = eval('(' + result + ')');//eval()解析单个json对象
            myApp.alert(_(_result.msginfo),function(){
            	myApp.closeModal(".modify_pop_box");
            	OrderSearch();//搜索订单8-28  
            });
           
        }
        
    });
   
}


function categoryTypeShow(type){
	var type = $(type).attr("lang");           

    //白钻、彩钻
    if(type==1 || type==2){
	//净度
   		$(".clarity").show();
   		$(".clarityDesc").show();
    }else{
    	$(".clarity").hide();
    	$(".clarityDesc").hide();
    } 
	
}

   
